from fastapi import Request
from tortoise.transactions import in_transaction

from service import UserService, SongService
from common.result.Result import Result
from common.enum import BaseEnum
from util.log import Log
from util.str import Str
from util.token import Token

class Body:
    songId: int
    sheetId: str

async def UpdateSongFavorite(req: Request, body: dict):
    try:
        async with in_transaction() as connection:
            songId = body.get("songId")
            sheetId = body.get("sheetId")
            if Str.isBlank(songId, sheetId):
                return Result.error(BaseEnum.PARAMETER_INVALID_ERROR)

            token = req.headers.get("token")
            user = await UserService.getUserByToken(token)
            if user == None:
                return Result.error(BaseEnum.USER_NOT_EXISTS_ERROR)

            res = await SongService.updateSongFavorite({
                'songId': songId,
                'userId': user.id,
                'sheetId': sheetId
            })

            # 将 song 收藏到了相同的歌单（非 i like 歌单）
            if res == 1:
                return Result.error(BaseEnum.FAVORITE_SONG_REPEATE_ERROR)

            return Result.success(res)
    except Exception as e:
        Log.error('更新 song 收藏记录异常', e)
        return Result.error(BaseEnum.SERVICE_ERROR)



